package com.neusoft.elmboot.util;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.elmboot.mapper.BusinessMapper;
import com.neusoft.elmboot.mapper.DeliveryAddressMapper;
import com.neusoft.elmboot.mapper.FoodMapper;
import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.po.Business;
import com.neusoft.elmboot.po.DeliveryAddress;
import com.neusoft.elmboot.po.Food;
import com.neusoft.elmboot.po.User;

/**
 * @author chj
 * @date 2024年9月6日
 */
/**
 * 在静态工具类中注入mapper的方式示例
 */
@Component
public class Lock {
	@Autowired
	private BusinessMapper businessMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private FoodMapper foodMapper;

	@Autowired
	private DeliveryAddressMapper deliveryAddressMapper;

	private static Lock Lock;
	
	@PostConstruct
    public void init(){
		Lock = this;
		Lock.deliveryAddressMapper = this.deliveryAddressMapper;
		Lock.foodMapper = this.foodMapper;
		Lock.userMapper = this.userMapper;
		Lock.businessMapper = this.businessMapper;
    }

	public static boolean BusinessLock(Business business) {
		// 验证商家Id和password匹配
		// 不匹配不能修改商家的信息，对食物，商家信息修改时应该进行调用进行判断
		String passwordIn = business.getBusinessPassword();
		String passwordDB = Lock.businessMapper.getBusinessById(business.getBusinessId()).getBusinessPassword();
		return passwordDB.equals(passwordIn);
	}

	public static boolean AddressLock(DeliveryAddress deliveryAddresss) {
		String UserIn = deliveryAddresss.getUserId();
		Integer id = deliveryAddresss.getDaId();
		if (Lock.deliveryAddressMapper == null) {
			return false;
		}
		DeliveryAddress temp = Lock.deliveryAddressMapper.getDeliveryAddressById(id);
		if (temp == null) {
			return false;
		}
		String UserDB = temp.getUserId();
		return (UserDB == UserIn);
	}

	public static boolean UserLock(User user) {
		// 验证用户Id和password匹配
		// 不匹配不能修改用户的信息，对】购物车，订单，地址，用户信息修改时应调用进行判断
		User temp = Lock.userMapper.getUserByIdByPass(user);
		return !(temp == null);
	}

	public static boolean FoodCountLock(Integer foodCount) {
		// 验证食物数量小于对应ordersdetailet的quantity
		// 用于点餐进行食物增加的验证，并且在save时也进行验证
		return foodCount >= 0;
	}

	public static boolean FoodInfoLock(Food food) {
		// 用于修改食物信息时
		// 验证食物是否属于商家，不属于不能修改商品信息
		if(food == null) {
			return false;
		}
		int businessIdIn = food.getBusinessId();
		int foodId = food.getFoodId();
		int businessIdDB = Lock.foodMapper.getFoodById(foodId).getBusinessId();
		return businessIdIn == businessIdDB;
	}

	public static boolean EmptyLock(Integer num) {
		// 用于实现将密码单向加密后再存⼊数据库的功能。
		return num > 0;
	}
}
